<template>
  <el-dialog v-model="addRoleVisible" title="添加角色">
    <el-form :model="roleForm" :rules="rules" ref="addRoleRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addRoleVisibleController(false)">取消</el-button>
        <el-button type="primary" @click="onSubmitUpdate(addRoleRef)"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="labelDialog" setup>
  import { reactive, ref } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { addRoleRequest } from '@/network/api/rights-api'
  import notification from '@/utils/notification'
  let addRoleVisible = ref(false)
  const addRoleRef = ref<FormInstance>()
  const rules = reactive<FormRules>({
    roleName: [
      { required: true, message: '角色名称为必填项~', trigger: 'blur' },
      { min: 2, max: 15, message: '角色名称长度在2-15个字符之间~', trigger: 'blur' },
    ],
  })
  const roleForm = reactive({
    roleName: '',
  })
  const emits = defineEmits(['onAddRole'])

  const onSubmitUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async valid => {
      if (valid) {
        const result = await addRoleRequest(roleForm.roleName)
        emits('onAddRole')
        addRoleVisibleController(false)
        notification.success(result.msg)
      } else {
        return
      }
    })
  }
  const addRoleVisibleController = (isClose: boolean) => {
    if (isClose) {
      addRoleVisible.value = true
    } else {
      addRoleVisible.value = false
    }
  }
  defineExpose({ addRoleVisibleController })
</script>

<style scoped></style>
